using System;
using System.Windows.Forms;

namespace Tsanie.ShellExtension.Util {

    public static class ControlExtension {
        public static void SafeRun(this Control control, Action action) {
            if (control == null || action == null)
                return;
            if (control.InvokeRequired)
                control.Invoke(action);
            else
                action();
        }
    }

    public static class ThreadExtension {

        public static void Cancel(this System.Timers.Timer timer) {
            if (timer != null)
                timer.Close();
        }

        public static void Cancel(this System.Threading.Thread thread) {
            if (thread != null && thread.ThreadState != System.Threading.ThreadState.Stopped)
                thread.Abort();
        }

        public static System.Timers.Timer SetTimeout(double interval, Action<System.Timers.ElapsedEventArgs> action) {
            System.Timers.Timer timer = new System.Timers.Timer(interval);
            timer.Elapsed += (sender, e) => {
                action.SafeRun(e);
                timer.Close();
            };
            timer.Start();
            return timer;
        }

        public static System.Timers.Timer CreateTimer(
            this System.Timers.Timer timer,
            double interval,
            Action<System.Timers.ElapsedEventArgs> action
        ) {
            timer.Cancel();
            timer = new System.Timers.Timer(interval);
            timer.Elapsed += (sender, e) => { action.SafeRun(e); };
            return timer;
        }

        public static System.Timers.Timer CreateTimeout(
            this System.Timers.Timer timer,
            double interval,
            Action<System.Timers.ElapsedEventArgs> action
        ) {
            timer.Cancel();
            return SetTimeout(interval, action);
        }
    }
}
